package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	_ "io/ioutil"
	"logScript/utils"
	_ "logScript/utils"
	"net/http"
	_ "net/http"
	"os"
	"strings"
	"time"
)

// LogPath 使用的地址
var LogPath = ""

// context post设置头部信息
var context = `{"info": {"_postman_id": "f351f865-a85d-472a-84f6-6cbf40c3b765","name": "自动化测试","schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},"item":[`

//程序入口
func main() {

	LogPath = utils.GetLogPath()

	//处理请求
	http.HandleFunc("/getPostManScript", postManScript)
	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		fmt.Println(" HTTP server start gailed,err:%v", err)
		return
	}
}

//请求方法
func postManScript(w http.ResponseWriter, r *http.Request) {
	//读取get请求参数
	query := r.URL.Query()
	date := query.Get("date")
	testName := query.Get("testName")
	ds := query.Get("ds")
	fmt.Printf("传入参数-------->date:%v ; testName:%v ; ds:%v\n", date, testName, ds)

	//读取文件
	str := Read0(date, testName, ds)

	w.Header().Set("content-type", "application/json")
	if len(str) < 700 {
		errorMap := make(map[string]string, 2)
		errorMap["code"] = "500"
		errorMap["msg"] = "无数据"
		msg, _ := json.Marshal(errorMap)
		w.Write(msg)
	} else {
		var dat map[string]interface{}
		error := json.Unmarshal([]byte(str), &dat)
		if error != nil {
			fmt.Printf("返回数据异常 %v\n", error)
		}
		msg, _ := json.Marshal(dat)
		w.Write(msg)
	}
}

func Read0(date, testName, discardServer string) string {

	//查询配置服务的url
	pathMap := utils.GetDoc()

	//fmt.Printf("pathMap-->%v\n", pathMap)

	//时间转换 "2006-01-02 15:04:05" 固定
	paramDate, _ := time.Parse("2006-01-02 15:04:05", date)

	fi, err := os.Open(LogPath)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return "异常"
	}
	defer fi.Close()

	contextCopy := context
	if testName != "" {
		contextCopy = strings.ReplaceAll(contextCopy, "自动化测试", testName)
	}
	br := bufio.NewReader(fi)
	lineNum := 0
	for {
		aline, c := br.ReadString('\n')
		if c == io.EOF {
			break
		}
		lineNum++
		fmt.Printf("lineNum ------> %v\n", lineNum)
		dateStr := aline[0:25]

		//日志时间转换
		logDate, _ := time.Parse(time.RFC3339, dateStr)
		logDate = logDate.Add(8 * time.Hour)

		if logDate.Unix() > paramDate.Unix() {
			repStr := strings.Replace(aline, "http:// { {url} } ", "http://{{url}}", -1)
			repStr = strings.Replace(repStr, "{ { token } }", "{{token}}", -1)
			//配置名称
			afterContext, result := dealContext(repStr, discardServer, pathMap)
			if !result {
				continue
			}

			defer func() {
				if r := recover(); r != nil {
					// 这里可以对异常进行一些处理和捕获
					fmt.Printf("Recovered: %v\n", r)
				}
			}()
			contextCopy = contextCopy + afterContext
		}
	}
	newContext := contextCopy[0:len(contextCopy)-1] + "],\"event\": [\n\t\t{\n\t\t\t\"listen\": \"prerequest\",\n\t\t\t\"script\": {\n\t\t\t\t\"type\": \"text/javascript\",\n\t\t\t\t\"exec\": [\n\t\t\t\t\t\"\"\n\t\t\t\t]\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t\"listen\": \"test\",\n\t\t\t\"script\": {\n\t\t\t\t\"type\": \"text/javascript\",\n\t\t\t\t\"exec\": [\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"pm.test(\\\"Status code is 200\\\", function () {\",\n\t\t\t\t\t\"    pm.response.to.have.status(200);\",\n\t\t\t\t\t\"});\",\n\t\t\t\t\t\"pm.test(\\\"Response time is less than 200ms\\\", function () {\",\n\t\t\t\t\t\"    pm.expect(pm.response.responseTime).to.be.below(200);\",\n\t\t\t\t\t\"});\"\n\t\t\t\t]\n\t\t\t}\n\t\t}\n\t]}"
	return newContext
}

//处理内容
//befContext 处理前的内容 pathMap 路径map
func dealContext(befContext, discardServer string, pathMap map[string]map[string]string) (string, bool) {

	//文件上传、js文件、OPTIONS请求 过滤
	if utils.NoContainsParam(befContext) {
		return "", false
	}

	//过滤请求
	if "" != discardServer {
		discardServers := strings.Split(discardServer, ",")
		for _, v := range discardServers {
			if strings.Contains(befContext, "http://{{url}}/"+v) {
				return "", false
			}
		}
	}

	befContext = befContext[25 : len(befContext)-2]

	contextMap := make(map[string]interface{})
	err := json.Unmarshal([]byte(befContext), &contextMap)
	if err != nil {
		fmt.Printf("转换异常%v；异常数据：%v\n", err, befContext)
	}
	fmt.Printf("befContext---->%v\n", befContext)
	for k, v := range pathMap {
		strUrl := contextMap["request"].(map[string]interface{})["url"]
		strMethod := contextMap["request"].(map[string]interface{})["method"]
		if "OPTIONS" == strings.ToUpper(strMethod.(string)) {
			return "", false
		}
		if strings.Index(strUrl.(string), k) > -1 && strMethod == v["method"] {
			contextMap["name"] = v["name"]
			break
		}
	}
	dataType, _ := json.Marshal(contextMap)
	dataString := string(dataType) + ","
	return dataString, true
}
